package com.ling.sdk.utils

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.telephony.TelephonyManager
import com.ling.sdk.live.LiveManager

/**
 * Created by MinF on 2017/7/8 0008.
 */
//@keep
class NetworkStateReceiver : BroadcastReceiver() {

    var token: String? = null


    private var lastType = -10086
    private var lastState: Boolean? = false

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action
        if (action == ConnectivityManager.CONNECTIVITY_ACTION) {
            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val info = connectivityManager.activeNetworkInfo
            currentNetWorkInfo = info
            // 和上一次的比较如果不一样 那么就通知下去
            if ((info?.isConnected) != lastState || lastType != info?.type)
                LiveManager.dispatchNetworkChange(token, info?.isConnected ?: false, info?.type
                        ?: -1)

            lastType = info?.type ?: -10086
            lastState = info?.isConnected

        }

    }

    companion object {
        var currentNetWorkInfo: NetworkInfo? = null
        @JvmStatic
        fun getCurrentNetworkType(): Int {
            return currentNetWorkInfo?.type ?: -1
        }

        @JvmStatic
        fun getCurrentNetworkIsConnect(): Boolean {
            return currentNetWorkInfo?.isConnected ?: false
        }
    }


    /**
     * 判断WIFI是否打开

     * @param context
     * *
     * @return
     */
    fun isWifiEnabled(context: Context): Boolean {
        val mgrConn = context
                .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val mgrTel = context
                .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return mgrConn.activeNetworkInfo != null && mgrConn
                .activeNetworkInfo.state == NetworkInfo.State.CONNECTED || mgrTel
                .networkType == TelephonyManager.NETWORK_TYPE_UMTS
    }
}